/*
 * Copyright (C) 2010 Mamadou Diop.
 *
 * Contact: Mamadou Diop <diopmamadou(at)doubango.org>
 *	
 * This file is part of imsdroid Project (http://code.google.com/p/imsdroid)
 *
 * imsdroid is free software: you can redistribute it and/or modify it under the terms of 
 * the GNU General Public License as published by the Free Software Foundation, either version 3 
 * of the License, or (at your option) any later version.
 *	
 * imsdroid is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU General Public License for more details.
 *	
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

package org.doubango.FrCall.Screens;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.doubango.FrCall.FrCall;
import org.doubango.FrCall.R;
import org.doubango.FrCall.Screens.chat.ScreenChat;
import org.doubango.FrCall.model.User;
import org.doubango.ngn.media.NgnMediaType;
import org.doubango.ngn.model.NgnHistoryEvent;
import org.doubango.ngn.model.NgnHistorySMSEvent;
import org.doubango.ngn.utils.NgnListUtils;
import org.doubango.ngn.utils.NgnPredicate;
import org.doubango.ngn.utils.NgnStringUtils;

import android.app.Activity;
import android.content.Context;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 最新信息界面
 */
public class ScreenNewMessage extends BaseScreen {

	private static String TAG = ScreenNewMessage.class.getCanonicalName();
	private ListView listView;
	private static MyAdapter adapter;
	public static List<User> friends;
	private static List<NgnHistoryEvent> msgList = new ArrayList<NgnHistoryEvent>();
	private User user;
	private TextView sysMsgCount;
	private ImageView sysMsgTip;
	public ScreenNewMessage() {
		super(SCREEN_TYPE.NEW_MSG_T, TAG);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_new_message);
		sysMsgTip = (ImageView) findViewById(R.id.screen_msg_message_tip);
		sysMsgTip.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				mScreenService.show(ScreenSystemMessages.class, ScreenSystemMessages.class.getCanonicalName(), "系统消息");
			}
		});
		sysMsgCount = (TextView) findViewById(R.id.screen_msg_message_count);
		if(friends==null)
			friends = new ArrayList<User>();
		listView = (ListView) findViewById(R.id.list);
		adapter = new MyAdapter(this);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adv, View v, int pos, long id) {
				User user = (User) friends.get(pos);
				selFriend = user;
				selFriend.setHasNewMsg(false);
				selFriend.setNewMsgNum(0);
				mScreenService.show(ScreenChat.class, null,true);
				return;
			}
		});
		refresh();
	}
	private void refresh() {
		sysMsgCount.setText(sysDB.getCountStr(FrCall.user.getUserId()));
	}
	public static final int HANDLE_REFRESH_LIST_VIEW = 0;
	public static final int HANDLE_TOAST_SHOW_LIST = 1;

	public static String sToastText = "";
	private Handler hander = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {

			case HANDLE_REFRESH_LIST_VIEW:
				adapter.notifyDataSetChanged();
				break;

			case HANDLE_TOAST_SHOW_LIST:
				cancelInProgress();
				Toast.makeText(getApplicationContext(), sToastText,
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	protected void onResume() {
		adapter.refresh();
		refresh();
		super.onResume();
	}

	protected void onDestroy() {
		super.onDestroy();
	}
	
	/**
	 * 发消息
	 */
	public static void addMessage(NgnHistorySMSEvent e, User user) {
		if(friends==null)
			friends = new ArrayList<User>();
		boolean exist = false;
		User temp;
		for (int i = 0; i < friends.size(); i++) {
			temp = friends.get(i);
			if (temp.getUserId().trim().equals(user.getUserId().trim())) {
				temp.setHasNewMsg(true);
				temp.addMsg();
				exist = true;
				break;
			}
		}

		if (!exist) {
			user.setHasNewMsg(true);
			user.addMsg();
			friends.add(user);
		}
			
		msgList.add(e);
		adapter.refresh();
	}
	
	/**
	 * HistoryEventSMSFilter
	 */
	class HistoryEventChatFilter implements NgnPredicate<NgnHistoryEvent> {
		@Override
		public boolean apply(NgnHistoryEvent event) {
			if (event != null && (event.getMediaType() == NgnMediaType.SMS)) {
				return NgnStringUtils.equals(user.getUserId(), event.getRemoteParty(), false);
			}
			return false;
		}
	}

	/**
	 * DateComparator
	 */
	class DateComparator implements Comparator<NgnHistoryEvent> {
		@Override
		public int compare(NgnHistoryEvent e1, NgnHistoryEvent e2) {
			return (int) (e1.getStartTime() - e2.getStartTime());
		}
	}

	private class MyAdapter extends BaseAdapter {

		private final Activity activity;
		protected LayoutInflater mLayoutInflater;
		private final Handler mHandler;
		
		public MyAdapter(Activity a) {
			activity = a;
			mHandler = new Handler();
			mLayoutInflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		// FIXME
		public void refresh() {
			
			if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
				notifyDataSetChanged();
			} else {
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						notifyDataSetChanged();
					}
				});
			}
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

		@Override
		public int getCount() {
			return friends.size();
		}

		@Override
		public User getItem(int position) {
			return friends.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			
			if (friends == null || position >= friends.size())
				return null;
			
			final ViewHolder holder;
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(
						R.layout.screen_new_message_item, null, false);
				holder = new ViewHolder();
				holder.avatar = (ImageView) convertView.findViewById(R.id.user_icon);
				holder.msgIcon = (ImageView) convertView.findViewById(R.id.msg_icon);
				holder.name = (TextView) convertView.findViewById(R.id.user);
				holder.msg = (TextView) convertView.findViewById(R.id.msg);
				holder.tipIcon = (ImageView) convertView.findViewById(R.id.tip);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			user = friends.get(position);
			
			if (user.getHasNewMsg()) {
				ColorMatrix colorMatrix = new ColorMatrix();
				colorMatrix.setSaturation(1);
				ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(
						colorMatrix);
				holder.avatar.setColorFilter(colorMatrixFilter);
				holder.name.setTextColor(ScreenNewMessage.this.getResources()
						.getColor(R.color.color_blue));
				holder.msgIcon.setVisibility(View.VISIBLE);
			} else {
				ColorMatrix colorMatrix = new ColorMatrix();
				colorMatrix.setSaturation(0);
				ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(
						colorMatrix);
				holder.avatar.setColorFilter(colorMatrixFilter);
				holder.name.setTextColor(ScreenNewMessage.this.getResources()
						.getColor(R.color.color_black));
				holder.msgIcon.setVisibility(View.INVISIBLE);
			}
			String text;
			if (user.getNewMsgNum() == 0) {
				text = user.getDisplayName() + "[" + user.getTotalMsgNum() + "]";
			}else {
				text = user.getDisplayName() + "[" + user.getNewMsgNum() + "/" + user.getTotalMsgNum() + "]";
			}
			holder.name.setText(text);
			
			// 用户过滤
			List<NgnHistoryEvent>  mChatList = NgnListUtils.filter(msgList, new HistoryEventChatFilter());
			// 时间排序
			Collections.sort(mChatList, new DateComparator());
			holder.msg.setText(((NgnHistorySMSEvent)mChatList.get(mChatList.size() - 1)).getContent());
			
			holder.tipIcon.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					selFriend = friends.get(position);
					selFriend.setHasNewMsg(false);
					selFriend.setNewMsgNum(0);
//					mScreenService.show(ScreenFriendInfo.class, null, "联系人详情");
				}
			});

			return convertView;
		}

		private class ViewHolder {
			ImageView avatar;
			ImageView msgIcon;
			TextView name;
			TextView msg;
			ImageView tipIcon;
		}
	}
}
